/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.interaction3d.assembly.convert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Michael Nischt
 */
public class Smooth
{
    private final Object[] map;
    private final List<Integer> split = new ArrayList<Integer>();

    public Smooth(int positions)
    {
        map = new Object[positions];
    }

    public int apply(int position, int normal)
    {
        int index = position;
        if(map[position] == null)
        {
            map[position] = normal;
        }
        else if(map[position] instanceof Integer)
        {
            int n = (Integer) map[position];
            if(n != normal)
            {
                Map<Integer,Integer> m = new HashMap<Integer,Integer>();
                map[position] = m;
                m.put(n, position);

                index = map.length+split.size();
                split.add(position);
                m.put(normal, index);
            }
        }
        else //if (map[position] instanceof Map)
        {
            Map<Integer,Integer> m = (Map<Integer,Integer>) map[position];

            Integer i = m.get(normal);
            if(i != null)
            {
                index = i;
            }
            else
            {
                index = map.length+split.size();
                split.add(position);
                m.put(normal, index);
            }
        }
        return index;
    }

    public int[] split()
    {
        int[] result = new int[split.size()];
        for(int i=0; i<result.length; i++)
        {
            result[i] = split.get(i);
        }
        return result;
    }
}